<style>

</style>
<template>
  <el-dialog
    title="数据源配置"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    width="40%"
    :before-close="clearForm">

    <el-form
      :label-position="labelPosition"
      label-width="120px"
      :model="saveData"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item label="选择域" prop="domainCode">
        <el-select
          :disabled="saveData.id && saveData.id !==''"
          filterable
          v-model="saveData.domainCode"
          placeholder="请选择域">
          <el-option
            v-for="item in domainOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据源名字" prop="dataSourceName">
        <el-input :disabled="saveData.id && saveData.id !==''" v-model="saveData.dataSourceName"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="saveData.desc"></el-input>
      </el-form-item>
      <el-form-item label="数据源类型" prop="dataSourceType">
        <el-select
          filterable
          @change="dataSourceTypeChange"
          v-model="saveData.dataSourceType"
          placeholder="请选择数据源类型">
          <el-option
            v-for="item in dataSourceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <template v-if="saveData.dataSourceType === 'SCRIPT'">
        <el-form-item label="脚本类型" prop="scriptInfo.scriptType">
          <el-select
            filterable
            v-model="saveData.scriptInfo.scriptType"
            placeholder="请选择脚本类型">
            <el-option
              v-for="item in scriptTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="脚本内容" prop="scriptInfo.scriptContent">
          <el-input :rows="10" type="textarea" placeholder="请输入脚本(脚本返回值必须为Map结构)" v-model="saveData.scriptInfo.scriptContent"></el-input>
        </el-form-item>
        <el-form-item label="执行超时时间" prop="scriptInfo.timeout">
          <el-input
            @change="scriptTimeChange"
            type="number" min="1"
            max="5"
            placeholder="脚本执行超时时间"
            v-model="saveData.scriptInfo.timeout"></el-input>
        </el-form-item>
      </template>
      <template v-if="saveData.dataSourceType === 'HTTP'">
        <el-form-item label="请求地址" prop="httpInfo.reqUrl">
          <el-input type="text" placeholder="HTTP请求地址" v-model="saveData.httpInfo.reqUrl"></el-input>
        </el-form-item>
        <el-form-item label="请求类型" prop="httpInfo.httpRequestType">
          <el-select
            filterable
            v-model="saveData.httpInfo.httpRequestType"
            placeholder="请选择请求类型">
            <el-option
              v-for="item in httpRequestTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="saveData.httpInfo.httpRequestType === 'POST'" label="请求地址" prop="httpInfo.reqParam">
          <el-input type="text" placeholder="HTTP请求参数" v-model="saveData.httpInfo.reqParam"></el-input>
        </el-form-item>
        <el-form-item label="执行超时时间" prop="scriptInfo.timeout">
          <el-input
            @change="httpTimeChange"
            type="number" min="1"
            max="5"
            placeholder="HTTP执行超时时间"
            v-model="saveData.httpInfo.timeout"></el-input>
        </el-form-item>
      </template>
      <el-form-item v-if="debugResult" label="测试结果">
        <div style="background-color: black;color:#FFD700;line-height: 20px!important;">
          <span>是否执行成功：{{ debugResult.success }}</span><br>
          <span v-if="saveData.dataSourceType === 'SCRIPT'"><span>脚本类型：{{ debugResult.scriptType }}<br></span></span>
          <span v-if="debugResult.success"><span>实际执行结果：{{ debugResult.realResult }}</span><br></span>
          <span v-if="!debugResult.success">执行异常：{{ debugResult.exceptionMessage }}</span>
        </div>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
    <el-button @click="clearForm">取 消</el-button>
       <el-button v-if="saveData.dataSourceType === 'SCRIPT'" type="warning" @click="debug">脚本测试</el-button>
       <el-button v-if="saveData.dataSourceType === 'HTTP'" type="warning" @click="debug">HTTP测试</el-button>
    <el-button :disabled="!testPass" type="primary" @click="save">确 定</el-button>
  </span>
  </el-dialog>
</template>
<script>

import {loadDataSourceTypeSelector, loadDomainSelector, loadHttpRequestTypeSelector, loadScriptTypeSelector} from "../../../api/loadSelectorApi";
import {dataSourceDebug, remoteValidateDataSourceName, saveDataSource} from "../../../api/dataSourceApi";

export default {
  name: "dataSourceForm",
  filters: {},
  components: {},
  data() {
    const validateDataSourceName = async (rule, value, callback) => {
      if (this.saveData.id) {
        callback()
      }
      if (this.saveData.domainCode === '') {
        callback(new Error("请先选择域"))
      }
      let ret = await remoteValidateDataSourceName(this.saveData.domainCode, value);
      if (ret.data.result) {
        callback()
      } else {
        callback(new Error("数据源名字不能重复"))
      }
    };
    return {
      labelPosition: 'right',
      dialogVisible: false,
      saveData: {
        domainCode: '',
        dataSourceName: '',
        dataSourceType: '',
        desc: '',
        scriptInfo: {
          scriptType: '',
          scriptContent: '',
          timeout: 1,
        },
        httpInfo: {
          httpRequestType: '',
          reqUrl: '',
          reqParam: '',
          timeout: 1,
        },
        sqlInfo: {
          sql: '',
          timeout: 1
        }
      },
      dataSourceTypeOptions: [],
      scriptTypeOptions: [],
      httpRequestTypeOptions: [],
      domainOptions: [],
      rules: {
        domainCode: [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        dataSourceName: [
          {required: true, message: '此项必填', trigger: 'blur'},
          {validator: validateDataSourceName, trigger: 'blur'}
        ],
        dataSourceType: [
          {required: true, message: '此项必填', trigger: 'change'},
        ],
        'scriptInfo.scriptType': [
          {required: true, message: '此项必填', trigger: 'change'},
        ],
        'scriptInfo.scriptContent': [
          {required: true, message: '此项必填', trigger: 'change'},
        ],
        'scriptInfo.timeout': [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        'httpInfo.httpRequestType': [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        'httpInfo.reqUrl': [
          {required: true, message: '此项必填', trigger: 'blur'}
        ],
        'httpInfo.reqParam': [
          {required: true, message: '此项必填', trigger: 'change'}
        ],
        'httpInfo.timeout': [
          {required: true, message: '此项必填', trigger: 'blur'}
        ],
      },
      testPass: false,
      debugResult: undefined
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    async load(data) {
      let vm = this
      vm.domainOptions = await loadDomainSelector();
      vm.dataSourceTypeOptions = await loadDataSourceTypeSelector();
      vm.scriptTypeOptions = await loadScriptTypeSelector();
      vm.httpRequestTypeOptions = await loadHttpRequestTypeSelector();
      if (data) {
        vm.saveData = vm.$cloneObj(data)
      }
      vm.dialogVisible = true
    },
    save() {
      let vm = this
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          await vm.doSave(this.saveData)
        }
      })
    },
    async doSave(saveData) {
      let vm = this
      let ret = await saveDataSource(saveData);
      if (ret.ok) {
        vm.$message({type: 'success', message: '保存成功!'});
      } else {
        vm.$message({type: 'error', message: '保存失败：' + ret.message});
      }
      vm.clearForm()
      vm.$parent.query()
    },
    debug() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let ret = await dataSourceDebug(this.saveData);
          if (ret.ok) {
            this.debugResult = ret.data.result
            this.testPass = this.debugResult.success
          } else {
            this.$message({type: 'error', message: '测试失败：' + ret.message});
          }
        }
      })
    },
    clearForm() {
      let vm = this
      try {
        vm.debugResult = undefined
        vm.saveData = {
          domainCode: '',
          dataSourceName: '',
          dataSourceType: '',
          desc: '',
          scriptInfo: {
            scriptType: '',
            scriptContent: '',
            timeout: 1,
          },
          httpInfo: {
            httpRequestType: '',
            reqUrl: '',
            reqParam: '',
            timeout: 1,
          },
          sqlInfo: {
            sql: '',
            timeout: 1
          }
        }
        vm.$refs['ruleForm'].resetFields()
      } catch (e) {
        console.log(e)
      }
      vm.dialogVisible = false
    },
    scriptTimeChange() {
      if (this.saveData.scriptInfo.timeout <= 0) {
        this.saveData.scriptInfo.timeout = 1
      } else if (this.saveData.scriptInfo.timeout > 5) {
        this.saveData.scriptInfo.timeout = 5
      }
    },
    httpTimeChange() {
      if (this.saveData.httpInfo.timeout <= 0) {
        this.saveData.httpInfo.timeout = 1
      } else if (this.saveData.httpInfo.timeout > 5) {
        this.saveData.httpInfo.timeout = 5
      }
    },
    dataSourceTypeChange() {
      this.testPass = false
      this.debugResult = undefined
    }
  }
}
</script>
